import time,re
import pandas as pd
import redis
import pickle
import logging
import pywencai
import akshare as ak
import pandas as pd
import configparser
import datetime
from sqlalchemy import create_engine,text
import pymysql
import os




pymysql.install_as_MySQLdb()


log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

pid = os.getpid()
query_date = datetime.datetime.now().strftime('%Y%m%d')

# 日志文件路径
log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'log/{pid}.log')

# 创建一个 handler，用于写入日志文件
file_handler = logging.FileHandler(log_file_path)
file_handler.setFormatter(logging.Formatter(log_format, date_format))
# 添加 handler 到 logger
logging.getLogger().addHandler(file_handler)

# 初始化配置解析器
config = configparser.ConfigParser()

# 读取配置文件
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini', encoding='utf-8')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'

engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)


# subscriber = r.pubsub()
# subscriber.subscribe('bjzt_channel')

query_date = datetime.datetime.now().strftime('%Y%m%d')
# query_date = datetime.datetime.now().strftime('%Y-%m-%d')


def get_next_trade_date(trade_date):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    # 筛选出所有晚于给定交易日的日期
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] > pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=True)  # 按日期升序排序
    next_trade_date = date_df["trade_date"].values[0]  # 获取最接近给定日期的下一个交易日
    return next_trade_date.strftime("%Y%m%d")  # 格式化日期

# 定义获取前一个交易日的函数
def get_pre_trade_date(trade_date):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] < pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=False)
    pre_trade_date = date_df["trade_date"].values[0]
    return pre_trade_date.strftime("%Y%m%d")

def get_pre_trade_date_n(trade_date,n):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] < pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=False)
    pre_trade_date = date_df["trade_date"].values[n-1]
    return pre_trade_date.strftime("%Y%m%d")

def get_dxjl_stock(query_date):
    sql = f'''
            select * from real_market_info_dxjl_h rmidh where trade_type in ('笼子触涨停','逼近涨停') and Date(`timestamp`) ='{query_date}'
        '''
    print(sql)
    df_dxjl = pd.read_sql(sql, engine)
    df_dxjl = df_dxjl.sort_values(by="timestamp",ascending=True)
    return df_dxjl

def startProcess():
    import subprocess
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 定义要运行的脚本的完整路径
    script_path = os.path.join(current_dir, "首板战法回测.py")
    processes = []
    for _ in range(10):
        p = subprocess.Popen(['/home/stock/python/bin/python', script_path])
        processes.append(p)

    try:
        # 等待直到所有子进程结束
        for process in processes:
            process.wait()
    except KeyboardInterrupt:
        # 当收到中断信号时，终止所有子进程
        print("Interrupt signal received. Terminating processes...")
        for process in processes:
            process.terminate()

def get_pre_trade_date_n(trade_date,n):
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"] < pd.Timestamp(trade_date).date()]
    date_df = date_df.sort_values(by="trade_date", ascending=False)
    pre_trade_date = date_df["trade_date"].values[n-1]
    return pre_trade_date.strftime("%Y%m%d")

def main(query_time):


    with engine.connect() as connection:
        sql = f"DELETE FROM analysis_stock_step_test WHERE Date(`timestamp`) ='{query_time}'"
        print(sql)
        delete_statement = text(sql)
        result = connection.execute(delete_statement)
        connection.commit()
        print(result.rowcount, "rows deleted.")

    pre_day_20 = get_pre_trade_date_n(query_time.replace("-",""),20)
    df_dxjl = get_dxjl_stock(query_time)
    for index, row in df_dxjl.iterrows():
        row["query_time"] = query_time
        row["query_time_20"] = pre_day_20
        r.lpush('bjzt_channel_test', pickle.dumps(row))
        time.sleep(0.1)






if __name__ == "__main__":
    r.delete('bjzt_channel_test')
    startProcess()


    # logging.info("监控进程启动")
    # # main("2024-4-26")
    # main("2024-4-24")
    # main("2024-4-23")
    # main("2024-4-22")
    # main("2024-4-26")
    # main("2024-4-18")
    # main("2024-4-19")
    # main("2024-4-17")
    # main("2024-4-16")
    # main("2024-4-12")
    # main("2024-5-9")
    # main("2024-5-8")
    # main("2024-5-7")
    # main("2024-5-6")










